<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Goods;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    // ->with(['goods'])
                    ->where($where)
                    ->where('type',1)
                    ->order($sort, $order)
                    ->paginate($limit)->each(function($item,$key){
                        $cate_title = Db::name('cate_goods')->where('id',$item['cate_pid'])->field('pid,title')->find();
                        if(isset($cate_title))
                        {
                            if(!empty($item['cate_id']))
                            {
                                $cate_name     = Db::name('cate_goods')->where('id',$item['cate_id'])->value('title');
                                $item['title'] = $cate_title['title']. ' L__ ' . $cate_name;
                            }else{
                                $item['title'] = $cate_title['title'];
                            }
                        }else{
                            $item['title'] = "";
                        }
                        
                        
                        
                        $basic = json_decode($item['item'],true);

                        $item['basicStr'] = $this->basicStr($basic);
//                        switch($item['status'])
//                        {
//                            case 1;
//                                $item['status'] = '是';
//                                break;
//                            case 2;
//                                $item['status'] = '否';
//                                break;
//                        }
                        return $item;
                });

            foreach ($list as $row) {
                $row->visible(['id','name','cate_id','image','num','money','gg','intro','vips','stock','integral','basicStr','status','title','create_time','cate_pid']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $goods = $this->request->post("");
            if ($params) {
                $data['name']      = $params['name'];
                $data['image']     = $params['image'];
//                $data['num']       = $params['num'];
                $data['item']      = $params['basic'];
                $data['desc']      = $params['desc'];
                $data['state']     = $params['state'];
//                $data['integer']   = $params['integer'];
//                $data['pool']      = $params['pool'];
//                $data['money']     = $params['money'];
//                $data['cate_pid']  = $params['cate_id'];
//                $data['cate_id']   = $params['cate_ids'];
                $data['create_time']  = time();
                $data['cate_pid']  = $goods['row']['cate_id'];
                $data['cate_id']  = $goods['row']['cate_ids'];

                $item = json_decode($data['item'],true);
                if(count($item) == 0)    $this->error(__('请输入规格'));

                foreach($item as $val)
                {
                    if(!$val['title'] || !$val['stock'] || !$val['intro'] || !$val['integral'])
                        $this->error(__('规格不能为空'));
                }


                $res = Db::name('goods')->where('id',$params['id'])->update($data);
                if($res)
                {
                    $this->success();
                }else{
                    $this->error(__('修改失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['cate_id'])
        {
            $cates = Db::name('cate_goods')->where('id',$row['cate_id'])->field('id,title')->find();
        }else{
            $cates = "";
        }
        $this->view->assign('cate',Db::name('cate_goods')->where(['pid'=>['=',0]])->field('id,title')->select());
        $this->view->assign('cates',$cates);
        $this->view->assign("row", $row);
        $this->view->assign('item',$row['item']);
        return $this->view->fetch();
    }



    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $data['name']      = $params['row']['name'];
                $data['image']     = $params['row']['image'];
//                $data['num']       = $params['row']['num'];
                $data['item']      = $params['row']['basic'];
                $data['desc']      = $params['row']['desc'];
                $data['cate_pid']  = $params['cate_id'];
                $data['cate_id']   = $params['cate_ids'];
//                $data['integer']   = $params['row']['integer'];
//                $data['pool']      = $params['row']['pool'];
//                $data['money']     = $params['row']['money'];
                $data['type']      = 1;
                $data['create_time']  = time();

                if(!$data['name'])    $this->error(__('请输入商品名称'));
                if(!$data['cate_pid'])$this->error(__('请选择商品分类'));

                $item = json_decode($data['item'],true);
                if(!$item)$this->error(__('请填写规格'));

                foreach($item as $val)
                {
                    if(!$val['title'] || !$val['stock'] || !$val['intro'] || !$val['integral'])
                        $this->error(__('规格不能为空'));
                }

                $res = Db::name('goods')->insert($data);
                if($res)
                {
                    $this->success();
                }else{
                    $this->error(__('添加失败'));
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign('cate',Db::name('cate_goods')->where(['pid'=>['>',0]])->field('id,title')->select());
        return $this->view->fetch();
    }


    // 商品分类
    public function category()
    {
        $pid = $this->request->get('cate_id', '');
        $categorylist = Db::name('cate_goods')->where(['pid'=>$pid])->field('id as value,title as name')->order('id desc')->select();
        $this->success('', '', $categorylist);
    }

    public function cates()
    {
        $data = $this->request->param();
        $res  = Db::name('cate_goods')->where('pid',$data['cate_id'])->field('id,title')->select();
        return json(['status'=>200,'data'=>$res]);
    }

    /*
     * 是否上下架
     *
     * */
    public function multi($ids = null)
    {
        $data = $this->request->param();

        $status = Db::name('goods')->where('id',$ids)->value('status');
        if($status == 1){
            $status = 2;
        }else{
            $status = 1;
        }
        $res = Db::name('goods')->where('id',$ids)->update(['status'=>$status]);
        if($res) {
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    
    
    public function basicStr($params)
    {
        // $str = "";
        $gg = "";
        $intro = "";
        $vips = "";
        $stock = "";
        $integral = "";
        if($params)
        {
            for($i = 0;$i < count($params);$i++)
            {
                $k = $i + 1;
                isset($params[$i]['vip_money']) ? $vip = $params[$i]['vip_money'] : $vip = "";
                // $str .= "规格" . $k .": ".$params[$i]['title'].' '.$params[$i]['intro'].' '.$vip.' '.$params[$i]['stock'].' '.$params[$i]['integral']. PHP_EOL;
                $gg         .= "规格" . $k .":". $params[$i]['title'] . PHP_EOL;
                $intro      .= $params[$i]['intro'] . PHP_EOL;
                $vips       .= $vip . PHP_EOL;
                $stock      .= $params[$i]['stock'] . PHP_EOL;
                $integral   .= $params[$i]['integral'] . PHP_EOL;
            }
        }
        return  ['gg'=>$gg,'intro'=>$intro,'vips'=>$vips,'stock'=>$stock,'integral'=>$integral];
    }



    public function __destruct()
    {
        // TODO: Implement __destruct() method.
    }
    
    
    
    /**
     * 联动搜索
     */
    public function cxselect()
    {
        $type = $this->request->get('type');
        $group_id = $this->request->get('group_id');
        $list = null;
        if ($group_id !== '') {
            if ($type == 'group') {
                $groupId = $this->auth->getChildrenGroupIds(true);
                
                $groupIds = Db::name('cate_goods')->where('pid',0)->field('id')->column('id','id');
                
                $list = Db::name('cate_goods')->where('id', 'in', $groupIds)->field('id as value,title as name')->select();
            } else {
                
                $list = Db::name('cate_goods')->where('id', 'in', $group_id)->field('id as value,title as name')->select();
            }
        }
        $this->success('', null, $list);
    }
    
    
}
